#include "awi_util.h"

uint8_t awi_check_le()
{
	union {
	 short int x;
	 char str[2];
	} v;

	v.x = 0x1122;
	return v.str[0] == (char)0x22;
}


uint8_t awi_check_be()
{
	union {
	 short int x;
	 char str[2];
	} v;

	v.x = 0x1122;
	return v.str[0] == (char)0x11;
}

uint8_t awi_atoi(const char *data, int bytes, int *num)
{
	typedef enum {
		_atoi_space,
		_atoi_sign,
		_atoi_num,
	}_atoi_state_t;
	const char *s, *e;
	uint8_t res = 0;
	_atoi_state_t state;
	int sign = 1;
	*num = 0;

	if (data == NULL) {
		return 0;
	}

	state = _atoi_space;
	s = data;
	e = data + bytes;
	while (s < e) {
		switch (state) {
		case _atoi_space:
			if (*s == ' ') {
				++s;
			}
			else {
				state = _atoi_sign;
			}
			break;
		case _atoi_sign:
			if (*s == '+') {
				++s;
			}
			else if (*s == '-') {
				sign = -1;
				++s;
			}
			state = _atoi_num;
			break;
		case _atoi_num:
			if (*s < '0' || *s > '9') {
				return 0;
			}
			*num = (*num) * 10 + (*s) - '0';
			res = 1;
			++s;
			break;
		}
	}

	*num = (*num) * sign;
	return res;
}

uint8_t awi_strncmp(const char *d1, int l1, const char* d2, int l2)
{
	if (l1 != l2) {
		return 0;
	}
	if (strncmp(d1, d2, l1) == 0) {
		return 1;
	}
	return 0;
}

#define BigLittleSwap16(A)  ((((uint16_t)(A) & 0xff00) >> 8) |	\
                             (((uint16_t)(A) & 0x00ff) << 8))

#define BigLittleSwap32(A)  ((((uint32_t)(A) & 0xff000000) >> 24) |	\
							 (((uint32_t)(A) & 0x00ff0000) >> 8) |	\
							 (((uint32_t)(A) & 0x0000ff00) << 8) |	\
							 (((uint32_t)(A) & 0x000000ff) << 24))



uint32_t checkCPUendian()
{
	static uint32_t checked = 0, endian;
	union{
		uint32_t i;
		uint8_t  s[4];
	}c;

	if (checked) return endian;

	c.i = 0x12345678;
	endian = (0x12 == c.s[0]);
	checked = 1;

	return endian;
}


uint32_t awi_htonl(uint32_t h)
{
	return checkCPUendian() ? h : BigLittleSwap32(h);
}


uint32_t awi_ntohl(uint32_t n)
{
	return checkCPUendian() ? n : BigLittleSwap32(n);
}


uint16_t awi_htons(uint16_t h)
{
	return checkCPUendian() ? h : BigLittleSwap16(h);
}


uint16_t awi_ntohs(uint16_t n)
{
	return checkCPUendian() ? n : BigLittleSwap16(n);
}